﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BCTMSRESTful.Configs
{
    internal class LowercaseDocumentFilter : IDocumentFilter
    {
        private readonly Regex regex = new Regex(@"([\w\/\-]*{)|(}[\w\/\-]*{)|(}[\w\/\-]*)|(^[\w\/\-]*$)", RegexOptions.IgnoreCase);

        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            //	generate the new keys
            var newPaths = new Dictionary<string, OpenApiPathItem>();
            var removeKeys = new List<string>();

            foreach (var path in swaggerDoc.Paths)
            {
                //var newKey = path.Key.ToLower();
                var newKey = this.regex.Replace(path.Key, m => m.Value.ToLowerInvariant());

                if (newKey != path.Key)
                {
                    removeKeys.Add(path.Key);
                    newPaths.Add(newKey, path.Value);
                }
            }

            //	add the new keys
            foreach (var path in newPaths)
            {
                swaggerDoc.Paths.Add(path.Key, path.Value);
            }

            //	remove the old keys
            foreach (var key in removeKeys)
            {
                swaggerDoc.Paths.Remove(key);
            }
        }
    }
}
